import requests
import time
import urllib3
import json
##cron: 35 21 * * *
##new Env("老六")
# 禁用SSL证书验证警告
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

# 企业微信机器人Webhook地址
WECHAT_WEBHOOK_URL = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=c4ed66c7-ea68-4b51-be3f-8319beb4504d"

def get_lottery_info(lottery_type):
    """
    获取彩票信息
    
    Args:
        lottery_type (int): 彩票类型 1=香港, 2=老奥, 5=新奥
    """
    url = f"https://6htv.frh51rth.com/gallerynew/h5/index/lastLotteryRecord?lotteryType={lottery_type}"
    
    cookies = {
        "Hm_lvt_fb7336fcaf32798958cc494bed7a2bb8": "1763293937, Hm_lpvt_fb7336fcaf32798958cc494bed7a2bb8=1763293937, HMACCOUNT=E342F11E378E0D06",
    }

    headers = {
        "user-agent": "Mozilla/5.0 (Linux; Android 14; 23127PN0CC Build/UKQ1.230804.001) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/131.0.6778.200 Mobile Safari/537.36",
        "accept": "application/json, text/plain, */*",
        "lotterytype": str(lottery_type),  # 根据lottery_type动态设置
        "sec-fetch-site": "same-origin",
        "sec-fetch-mode": "cors",
        "sec-fetch-dest": "empty",
        "referer": "https://6htv.frh51rth.com/",
        # 移除 accept-encoding 头，让 requests 自动处理编码
        "accept-language": "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7",
        "priority": "u=1, i"
    }

    try:
        # 添加verify=False来禁用SSL证书验证
        res = requests.get(url, headers=headers, cookies=cookies, timeout=10, verify=False)
        res.raise_for_status()  # 如果请求失败会抛出异常
        
        # 检查响应内容类型
        content_type = res.headers.get('content-type', '')
        if 'application/json' not in content_type:
            print(f"警告: 响应内容类型不是JSON: {content_type}")
            print(f"响应内容前100字符: {res.text[:100]}")
        
        # 尝试解析JSON
        try:
            # 显式设置编码为UTF-8
            if res.encoding is None or res.encoding.lower() != 'utf-8':
                res.encoding = 'utf-8'
            
            data = res.json()
        except json.JSONDecodeError as e:
            print(f"JSON解析错误: {e}")
            print(f"响应状态码: {res.status_code}")
            print(f"响应编码: {res.encoding}")
            print(f"响应内容: {res.text[:500]}")  # 打印前500个字符以便调试
            
            # 尝试使用其他常见编码
            for encoding in ['gbk', 'gb2312', 'big5', 'latin1']:
                try:
                    res.encoding = encoding
                    data = res.json()
                    print(f"使用编码 {encoding} 成功解析JSON")
                    break
                except:
                    continue
            else:
                # 所有编码尝试都失败
                return None
        
        # 检查响应是否成功
        if data.get("code") == 10000 and data.get("success"):
            return data
        else:
            print(f"请求失败: {data.get('msg', '未知错误')}")
            return None
            
    except requests.exceptions.RequestException as e:
        print(f"网络请求错误: {e}")
        return None

def parse_lottery_data(data, lottery_type):
    """
    解析彩票数据并返回格式化信息
    
    Args:
        data (dict): 彩票数据
        lottery_type (int): 彩票类型
    
    Returns:
        tuple: (详细信息字符串, 简要信息字符串)
    """
    if not data or "data" not in data:
        return "", ""
    
    lottery_data = data["data"]
    lottery_name_map = {1: "香港", 2: "老奥", 5: "新奥"}
    lottery_name = lottery_name_map.get(lottery_type, f"未知({lottery_type})")
    
    # 构建详细信息（用于控制台输出）
    detail_info = f"\n{'='*50}\n"
    detail_info += f"【{lottery_name}】彩票信息\n"
    detail_info += f"{'='*50}\n"
    
    # 基础信息
    detail_info += f"当前期数: 第{lottery_data.get('period', 'N/A')}期\n"
    detail_info += f"开奖日期: {lottery_data.get('lotteryTime', 'N/A')}\n"
    detail_info += f"下期期数: 第{lottery_data.get('nextLotteryNumber', 'N/A')}期\n"
    detail_info += f"下期开奖: {lottery_data.get('nextLotteryTime', 'N/A')}\n"
    
    # 开奖号码
    original_numbers = lottery_data.get('originalDataList', [])
    number_list = lottery_data.get('numberList', [])
    
    if original_numbers:
        # 修改开奖号码显示格式
        if len(original_numbers) >= 7 and len(number_list) >= 7:
            # 处理平码（前6个数字）
            normal_numbers = []
            for i in range(6):
                normal_number = original_numbers[i]
                normal_zodiac = number_list[i].get('shengXiao', '未知')
                normal_numbers.append(f"{normal_number}({normal_zodiac})")
            
            # 处理特码（第7个数字）
            special_number = original_numbers[6]
            special_zodiac = number_list[6].get('shengXiao', '未知')
            
            formatted_numbers = f"平:{' '.join(normal_numbers)} \n特:{special_number}({special_zodiac})"
        else:
            # 如果数字不足7个，保持原样显示
            formatted_numbers = ' '.join(original_numbers)
        detail_info += f"开奖号码: {formatted_numbers}\n"
    
    # 详细号码信息
    if number_list:
        detail_info += "\n详细号码分析:\n"
        for i, num_info in enumerate(number_list, 1):
            detail_info += (f"  号码{i}: {num_info.get('number', 'N/A')} - "
                          f"生肖:{num_info.get('shengXiao', 'N/A')} "
                          f"五行:{num_info.get('wuXing', 'N/A')} "
                          f"大小:{num_info.get('daXiao', 'N/A')} "
                          f"单双:{num_info.get('danShuang', 'N/A')}\n")
    
    # 构建简要信息（用于通知）
    brief_info = f"【{lottery_name}】\n"
    brief_info += f"第{lottery_data.get('period', 'N/A')}期\n"
    
    # 修改开奖号码显示格式
    if original_numbers:
        if len(original_numbers) >= 7 and len(number_list) >= 7:
            # 处理平码（前6个数字）
            normal_numbers = []
            for i in range(6):
                normal_number = original_numbers[i]
                normal_zodiac = number_list[i].get('shengXiao', '未知')
                normal_numbers.append(f"{normal_number}({normal_zodiac})")
            
            # 处理特码（第7个数字）
            special_number = original_numbers[6]
            special_zodiac = number_list[6].get('shengXiao', '未知')
            
            formatted_numbers = f"平:{' '.join(normal_numbers)} \n特:{special_number}({special_zodiac})"
        else:
            # 如果数字不足7个，保持原样显示
            formatted_numbers = ' '.join(original_numbers)
        brief_info += f"开奖号码: {formatted_numbers}\n"
    else:
        brief_info += f"开奖号码: N/A\n"
    
    brief_info += f"下期: 第{lottery_data.get('nextLotteryNumber', 'N/A')}期"
    
    return detail_info, brief_info

def send_wechat_work_notification(message, title="开奖信息"):
    """
    发送企业微信机器人通知
    
    Args:
        message (str): 通知内容
        title (str): 通知标题，默认为"开奖信息"
    """
    try:
        # 构建企业微信机器人消息格式
        payload = {
            "msgtype": "text",
            "text": {
                "content": f"{title}\n\n{message}"
            }
        }
        
        headers = {
            "Content-Type": "application/json"
        }
        
        response = requests.post(
            WECHAT_WEBHOOK_URL, 
            data=json.dumps(payload), 
            headers=headers,
            timeout=10
        )
        
        if response.status_code == 200:
            result = response.json()
            if result.get("errcode") == 0:
                print(f"企业微信通知发送成功: {title}")
            else:
                print(f"企业微信通知发送失败: {result.get('errmsg', '未知错误')}")
        else:
            print(f"企业微信通知发送失败，状态码: {response.status_code}")
            
    except Exception as e:
        print(f"企业微信通知发送失败: {e}")

def main():
    # 定义要查询的彩票类型
    lottery_types = [1, 2, 5]  # 1=香港, 2=老奥, 5=新奥
    
    all_brief_info = []  # 存储所有彩票类型的简要信息
    
    for i, lottery_type in enumerate(lottery_types):
        print(f"\n正在查询彩票类型 {lottery_type}...")
        
        # 获取数据
        data = get_lottery_info(lottery_type)
        
        if data:
            # 解析数据
            detail_info, brief_info = parse_lottery_data(data, lottery_type)
            
            # 输出详细信息到控制台
            print(detail_info)
            
            # 收集简要信息用于通知
            all_brief_info.append(brief_info)
        else:
            error_msg = f"彩票类型 {lottery_type} 数据获取失败"
            print(error_msg)
            all_brief_info.append(error_msg)
        
        # 如果不是最后一个，延时5秒
        if i < len(lottery_types) - 1:
            print(f"\n等待5秒后查询下一个...")
            time.sleep(5)
    
    # 发送汇总通知到企业微信
    if all_brief_info:
        notification_message = "\n\n".join(all_brief_info)
        send_wechat_work_notification(notification_message, "开奖信息汇总")
        
        # 同时在控制台输出通知内容
        print(f"\n{'='*50}")
        print("发送到企业微信的通知内容:")
        print(notification_message)
        print(f"{'='*50}")

if __name__ == "__main__":
    main()